package com.bishe.controller;

import com.bishe.pojo.FileInfo;
import com.bishe.pojo.response.Result;
import com.bishe.service.FileService;
import com.bishe.util.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 文件控制器
 */
@RestController
@RequestMapping("file")
@Api(tags = "文件控制层")
public class FileController {

    @Resource
    private FileService fileService;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file, String dataId) {
        fileService.upload(file, dataId);
        return Result.ok("上传成功!");
    }


    @ApiOperation("下载文件")
    @GetMapping("/download/{fileId}")
    public Result<?> download(@PathVariable String fileId, HttpServletResponse response) {
        FileInfo fileInfo = fileService.getById(fileId);
        FileUtils.download(response, FileUtils.getFile(fileInfo));
        return Result.ok();
    }


    @ApiOperation("删除文件")
    @DeleteMapping("/deleteFile/{fileId}")
    public Result<?> deleteFile(@PathVariable String fileId) {
        fileService.deleteFile(fileId);
        return Result.ok();
    }


    @ApiOperation("根据业务id获取文件")
    @GetMapping("/getById/{id}")
    public Result<FileInfo> getByDateId(@PathVariable String id) {
        FileInfo byId = fileService.getByDateId(id);
        return Result.ok("ok", byId);
    }

    @ApiOperation("获取头像")
    @GetMapping("/getPhoto/{id}")
    public Result<?> getPhoto(HttpServletResponse response, @PathVariable String id) {
        FileInfo fileInfo = fileService.getByDateId(id);
        if (fileInfo != null) {
            FileUtils.download(response, FileUtils.getFile(fileInfo));
            return Result.ok();
        }
        return null;
    }


}
